#include "dblink_string.h"
#include "cJSON.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
  * @brief  Get file-stream's length.
  * @Notes  None.
  * @param  fp, file pointer.
  * @retval stream's length which in a file.
  */
long fstr_len(FILE* fp)
{
	long stream_len; 
	fseek(fp, 0, SEEK_END); 
	stream_len = ftell(fp); 
	fseek(fp, 0, SEEK_SET);
	//printf("length=%d\n", stream_len);
	return stream_len;
}

/**
  * @brief  Allocate memory space for file-stream.
  * @Notes  None.
  * @param  fp, file pointer.
  * @param  stream, memory buffer for stream.
  * @retval stream's length which in a file.
  */
long fstr_alloc(FILE* fp, char** stream)
{
	long chars = fstr_len(fp);
	long rdsz;
	if(chars == 0)
	{
		return 0;
	}
	else{
		*stream = (char*)malloc((chars)*sizeof(char));
		rdsz = fread(*stream, 1, chars, fp);
		//printf("fstrbuf:%s\n", fstrbuf);
		return rdsz;
	}
}

/**
  * @brief  Release memory space of file-stream.
  * @Notes  None.
  * @param  fstrbuf, memory buffer for stream.
  * @retval None.
  */
void fstr_free(char* fstrbuf)
{
	if(fstrbuf != NULL)
		free(fstrbuf);
}

struct __mydb_conn_info  dblinkstring;
int load_mydb_conn_info(char* cfgfile)
{
	FILE* fp = NULL; 
	char* stream; long txtlen = 0;
	cJSON *json;
	if((fp=fopen(cfgfile, "r")) == NULL)	//尝试读文件
	{
		//cfgvar_default();
		fprintf(stderr, "cJSON/> {INFO} Config file '%s' load faild, Routine will use default configuration.\n", cfgfile);
		return 1;
	}
	else
	{
		txtlen = fstr_alloc(fp, &stream);
		//printf("%s\n", stream);
		json = cJSON_Parse(stream);

		/* 从配置文件中解析出参数 */
		strcpy(dblinkstring.host, cJSON_GetObjectItem(json, "host")->valuestring);
		strcpy(dblinkstring.user, cJSON_GetObjectItem(json, "user")->valuestring);
		strcpy(dblinkstring.pass, cJSON_GetObjectItem(json, "pass")->valuestring);
		strcpy(dblinkstring.db,   cJSON_GetObjectItem(json, "db")->valuestring);
		dblinkstring.port = cJSON_GetObjectItem(json, "port")->valueint;

		//strcpy(dblinkstring.sockpipe, cJSON_GetObjectItem(json, "sockpipe")->valuestring);
		if(strcmp("CLIENT_FOUND_ROWS", cJSON_GetObjectItem(json, "flag")->valuestring) == 0){
			dblinkstring.flag = CLIENT_FOUND_ROWS;
		}

		cJSON_Delete(json);
		fstr_free(stream);
		fclose(fp); fp=NULL;
		fprintf(stderr, "cJSON/> {INFO} Config file '%s' load success.\n", cfgfile);
	}

	return 0;
}


